﻿using System;
using System.Data.Linq;
using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;

namespace Estimate
{
    public partial class formProduct : FormMDIChildTemplate
    {
        public formProduct()
        {
            InitializeComponent();

        }

        ProductCategory currentCategory;
        StoreHouse currentStoreHouse;

        private void printToolStripButton_Click(object sender, EventArgs e)
        {
            reportProductPriceList reportProductPriceList = new reportProductPriceList();
            reportProductPriceList.bindingSourceCategory.DataSource = context.ProductCategories;

            reportProductPriceList.xrLabelFirm.Lines = db.GetFirmOwn().GetFullDescription();
            reportProductPriceList.ShowPreview();
        }

        private void formMaterialProduct_Load(object sender, EventArgs e)
        {
            LoadStoreHouse();
            root.TranslateGrid(gridProduct);
            root.TranslateGrid(gridHistory);
            unitBindingSource.DataSource = context.Units.ToList();
            LoadCategory();
            if (treeViewCategory.Nodes.Count <= 0) return;
            currentCategory = (ProductCategory)treeViewCategory.Nodes[0].Tag;
            LoadProducts();
        }


        private void LoadStoreHouse()
        { storeHouseBindingSource.DataSource = context.StoreHouses.ToList(); }



        #region LoadCategory
        private void LoadCategory()
        {
            treeViewCategory.Nodes.Clear();
            var rootCategories = context.ProductCategories.Where(x => x.ParentID == null);
            foreach (ProductCategory category in rootCategories) InsertNode(null, category);
        }

        private void InsertNode(TreeNode node, ProductCategory category)
        {
            TreeNode treeNode = new TreeNode();
            treeNode.Tag = category;
            treeNode.Text = category.ProductCategoryName;
            if (node == null) treeViewCategory.Nodes.Add(treeNode);
            else node.Nodes.Add(treeNode);
            foreach (ProductCategory subCategory in category.ProductCategories) InsertNode(treeNode, subCategory);
        }
        #endregion



        #region addCategory
        string NEW_CATEGORY_NAME = "Нова Категорія";

        private void buttonAddCategory_Click(object sender, EventArgs e)
        { AddCategory(true); }

        private void buttonAddSubcategory_Click(object sender, EventArgs e)
        { AddCategory(false); }

        void AddCategory(bool isRoot)
        {
            ProductCategory category = new ProductCategory();
            category.ProductCategoryName = NEW_CATEGORY_NAME;
            context.ProductCategories.InsertOnSubmit(category);
            if (!isRoot) category.ProductCategory1 = currentCategory;
            root.Submit(false);
            LoadCategory();
        }
        #endregion

        private void buttonDeleteCategory_Click(object sender, EventArgs e)
        {
            if (currentCategory != null)
            {
                if (currentCategory.ProductCategories.Count > 0 || currentCategory.Products.Count > 0)
                { formMain.ShowError("Неможливо Видалити Категорію"); return; }
                context.ProductCategories.DeleteOnSubmit(currentCategory);
                root.Submit(false);
            }
            LoadCategory();
        }

        private void buttonSaveCategory_Click(object sender, EventArgs e)
        {
            if (currentCategory != null)
            {
                currentCategory.ProductCategoryName = textBoxCategoryName.Text;
                root.Submit(false);
            }
            LoadCategory();
        }



       

        private void gridProduct_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
        {
            string Value = (string)e.Value;
            string columnName = gridProduct.Columns[e.ColumnIndex].Name.ToLower();
            if (columnName.Contains("unit"))
            {
                Unit unit = context.Units.Where(x => x.UnitName == Value).First();
                currentProduct.Unit = unit;
                e.Value = unit;
            }
            if (columnName.Contains("productcode")) currentProduct.ProductCode = Value;
            if (columnName.Contains("productname")) currentProduct.ProductName = Value;
            e.ParsingApplied = true;
        }




        #region StoreHouse
        private void storeHouseBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            currentStoreHouse = (StoreHouse) storeHouseBindingSource.Current;
            LoadProducts();
        }

        private void buttonStoreHouseEdit_Click(object sender, EventArgs e)
        {
            comboBoxStoreHouse.DropDownStyle = ComboBoxStyle.DropDown;
            this.ActiveControl = comboBoxStoreHouse;
        }

        private void comboBoxStoreHouseEndEdit()
        {
            string storeHouseNewName = comboBoxStoreHouse.Text;
            currentStoreHouse.StoreHouseName = storeHouseNewName;
            if (root.Submit())
            {
                comboBoxStoreHouse.DropDownStyle = ComboBoxStyle.DropDownList;
                LoadStoreHouse();
                comboBoxStoreHouse.Text = storeHouseNewName;
            }
        }

        private void comboBoxStoreHouse_KeyDown(object sender, KeyEventArgs e)
        { if (e.KeyCode == Keys.Return) comboBoxStoreHouseEndEdit(); }

        private void comboBoxStoreHouse_Click(object sender, EventArgs e)
        {
            if (comboBoxStoreHouse.DropDownStyle == ComboBoxStyle.DropDown)
                comboBoxStoreHouseEndEdit();
        }

        private void buttonStoreHouseAdd_Click(object sender, EventArgs e)
        {
            string storeHouseNewName = "Новий Склад";
            StoreHouse storeHouse = new StoreHouse();
            storeHouse.StoreHouseName = storeHouseNewName;
            context.StoreHouses.InsertOnSubmit(storeHouse);
            context.SubmitChanges();
            LoadStoreHouse();
            comboBoxStoreHouse.Text = storeHouseNewName;
        }

        private void buttonStoreHouseDelete_Click(object sender, EventArgs e)
        {
            if (currentStoreHouse.ProductHistories.Count == 0)
            {
                context.StoreHouses.DeleteOnSubmit(currentStoreHouse);
                root.Submit();
                LoadStoreHouse();
            }
            else { formMain.ShowError("Неможливо Видалити Склад"); }
        }
        #endregion

        #region LoadProducts
      
        private void checkBoxAllStoreHouse_CheckedChanged(object sender, EventArgs e)
        {
            comboBoxStoreHouse.Enabled = !checkBoxAllStoreHouse.Checked;
            LoadProducts();
        }

        private void checkBoxAllMaterial_CheckedChanged(object sender, EventArgs e)
        { LoadProducts(); }

        private void treeViewCategory_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            currentCategory = (ProductCategory)e.Node.Tag;
            LoadProducts();
        }

        private void LoadProducts()
        {
           IQueryable<Product>  products = context.Products;
            if (!checkBoxAllMaterial.Checked)
                products = products.Where(x => x.ProductCategory == currentCategory);

            var productsInStoreHouse = products.Select
                (product => new ProductInStoreHouse
                                {
                                    ProductCategory = product.ProductCategory,
                                    ProductCode = product.ProductCode,
                                    ProductId = product.ProductID,
                                    ProductName = product.ProductName,
                                    Unit = product.Unit
                                }).ToList();

            var storeHouses = new List<StoreHouse>();
            if (checkBoxAllStoreHouse.Checked) storeHouses.AddRange(context.StoreHouses);
            else storeHouses.Add(currentStoreHouse);

            foreach (var productInStoreHouse in productsInStoreHouse)
            {
                var cnt = 0m;
                foreach (var storeHouse in storeHouses)
                {
                    var cntIn =
                        storeHouse.ProductHistories.Where(
                            x =>
                            x.StatusID == 20 && x.StoreHouse == storeHouse &&
                            x.ProductID == productInStoreHouse.ProductId).Sum(
                            x => x.Cnt);
                    var cntOut =
                        storeHouse.ProductHistories.Where(
                            x =>
                            x.StatusID == 30 && x.StoreHouse == storeHouse &&
                            x.ProductID == productInStoreHouse.ProductId).Sum(
                            x => x.Cnt);

                    cnt += cntIn - cntOut;
                }
                productInStoreHouse.Count = cnt;
            }


            productInStoreHouseBindingSource.DataSource = productsInStoreHouse.ToList();
        }
        #endregion

        #region Products
        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            if (currentCategory != null)
            {
                Product product = new Product();
                product.ProductCategory = currentCategory;
                product.ProductName = "Новий Товар";
                product.ProductCode = "000";
                product.Unit = context.Units.First();
                context.Products.InsertOnSubmit(product);
                root.Submit();
                LoadProducts();
            }
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {

            if (currentProduct.ProductHistories.Count > 0)
            { formMain.ShowError("Неможливо Видалити Товар"); return; }
            else { context.Products.DeleteOnSubmit(currentProduct); root.Submit(); }
            LoadProducts();
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            root.Submit(false);
            LoadProducts();
        }

        #endregion

        Product currentProduct;
        private void productInStoreHouseBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            ProductInStoreHouse productInStoreHouse = (ProductInStoreHouse)productInStoreHouseBindingSource.Current;
            if (productInStoreHouse != null)
                currentProduct = context.Products.Where(x => x.ProductID == productInStoreHouse.ProductId).First();
            else currentProduct = null;
            LoadHistory();
        }

        private void LoadHistory()
        {
            historyBindingSource.DataSource = context.ProductHistories.Where(x => x.Product == currentProduct);
        }
    }
}